<template>
  <div>
    <el-upload
      ref="uploadEle"
      :action="UPLOAD_IMG_URL"
      :headers="headers"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :file-list="fileList"
      :limit="limit"
      :on-change="handleChange"
      :class="{ disabled: currentNum === limit }"
    >
      <el-icon v-if="currentNum < limit"><Plus /></el-icon>
    </el-upload>

    <el-dialog v-model="dialogVisible">
      <img
        w-full
        style="width: 100%"
        :src="dialogImageUrl"
        alt="Preview Image"
      />
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {ref, watch} from "vue";
import { Plus } from "@element-plus/icons-vue";
// @ts-ignore
import { ElMessage, ElUpload, UploadProps, UploadUserFile } from "element-plus";
import {UPLOAD_IMG_URL} from "@/utils/request";
const props = defineProps({
  limit: {
    type: Number,
    default: 1,
  },
  modelValue: String,
  validateEvent: {
    type: Boolean,
    default: true,
  },
});
const headers = {"Authorization":"Bearer " + window.localStorage.getItem("accessToken")}
const currentNum = ref(0);
const emit = defineEmits(["update:modelValue", "change"]);

const uploadEle = ref<InstanceType<typeof ElUpload>>();
const fileList = ref<UploadUserFile[]>([]);
const dialogImageUrl = ref("");
const dialogVisible = ref(false);

const handleRemove: UploadProps["onRemove"] = (
  uploadFile: any,
  uploadFiles: any
) => {
  console.log(uploadFile, uploadFiles);
  callFun(uploadFiles);
};

const handlePictureCardPreview: UploadProps["onPreview"] = (
  uploadFile: any
) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};

// 文件状态改变时，添加文件、上传成功和上传失败时都会被调用
const handleChange = (file: any, fileTempList: any) => {
  const typeArr = ["image/png", "image/gif", "image/jpeg", "image/jpg"];
  const isJPG = typeArr.indexOf(file.raw.type) !== -1;
  const isLt3M = file.size / 1024 / 1024 < 3;
  if (!isJPG) {
    ElMessage({
      message: "只能是图片",
      type: "error",
    });
    uploadEle.value?.clearFiles();
    return;
  }
  if (!isLt3M) {
    ElMessage({
      message: "上传图片大小不能超过 3MB!",
      type: "error",
    });
    uploadEle.value?.clearFiles();
    return;
  }
  if (file.status != "success") {
    return;
  }
  fileList.value = fileTempList;
  callFun(fileTempList);
};

const callFun = (fileTempList: any) => {
  if (fileTempList) {
    const urls: string[] = fileTempList.map((file: any) => file.response.url);
    currentNum.value = fileTempList.length;
    content.value = urls.join(",");
  }
};

const resetImg = () => {
  uploadEle.value?.clearFiles();
  fileList.value = [];
  currentNum.value = 0;
};

const revert_data = (d: any) => {
  emit("update:modelValue", d);
  emit("change");
  if (fileList.value.length == 0 && props.modelValue) {
    const urls = props.modelValue.split(",");
    urls.forEach((url) => {
      fileList.value.push({ url, response: { url } });
    });
    currentNum.value = fileList.value.length;
  }
  if (!d) resetImg();
};
console.log("props.modelValue", props.modelValue);

const content = ref<string>();
watch(props, (newVal) => (content.value = newVal.modelValue));
watch(content, (newVal) => revert_data(newVal));
content.value = props.modelValue;
</script>
